package main.java.eu.jpereira.trainings.designpatterns.structural.decorator.channel.decorator;

import java.util.ArrayList;
import java.util.regex.Pattern;

import main.java.eu.jpereira.trainings.designpatterns.structural.decorator.channel.SocialChannel;

public class WordCensor extends SocialChannelDecorator {
    ArrayList<String> words;
   
    public WordCensor(ArrayList<String> words){
                this(words, null);
    }
   
        public WordCensor(ArrayList<String> words, SocialChannel channel) {
                if(words == null)
                    this.words = new ArrayList<String>();
                else
                        this.words = words;
               
                this.delegate = channel;
        }

        public void addWordToList(String word){
                words.add(word);
        }
       
        /**
         * @param word to remove from list
         * @return true if word was removed, false if word wasn't found
         */
        public boolean removeWordFromList(String word){
                boolean removed = false;
                if(words.contains(word)){
                        removed = true;
                        words.remove(word);
                }
                return removed;
        }
       
        @Override
        public void deliverMessage(String message) {
                StringBuilder builder = new StringBuilder();
               
                builder.append(censor(message));

                if (delegate != null) {
                        delegate.deliverMessage(builder.toString());
                }
        }
       
        /**
         * First it removes all words specifies in arraylist words from the string,
         * then removes all whitespaces from the beginning and the end
         * and then turns all multiple whitespaces into a one, using \\s+ regex
         * @param msg
         * @return
         */
        private String censor(String msg){
                for(String word : words)
                        msg =  msg.replaceAll(Pattern.quote(word), "");
               
                return msg.trim().replaceAll("\\s+", " ");
        }
       
        public ArrayList<String> listOfWords(){
                return words;
        }

}